#include <QDir>
#include <QFileDialog>
#include <QFontDialog>
#include <QStyleFactory>

#include "formsettings.h"
#include "formmain.h"
#include "definitions.h"


FormSettings::FormSettings(QWidget *parent) : QDialog(parent), ui(new Ui::FormSettings) {
    ui->setupUi(this);
#ifdef Q_WS_MAC
    // Do not allow minimized window on mac.
    // See     qApp->setQuitOnLastWindowClosed(true);
    // note in FormMain
    ui->checkMinimized->hide();
#endif
    connect(ui->btnOk, SIGNAL(clicked()), this, SLOT(saveSettings()));
    connect(ui->btnBrowser, SIGNAL(clicked()), this, SLOT(selectBrowser()));
    connect(ui->btnCustomPath, SIGNAL(clicked()), this, SLOT(selectCustomFile()));
    connect(ui->txtBrowser, SIGNAL(textChanged(QString)), this, SLOT(checkBrowser()));
    connect(ui->cmbProxyType, SIGNAL(currentIndexChanged(int)), this, SLOT(enableProxy(int)));
    connect(ui->checkProxyPassword, SIGNAL(toggled(bool)), this, SLOT(setEchoPassword()));
    connect(ui->txtBrowserArgs, SIGNAL(textChanged(QString)), this, SLOT(informArgs()));
    connect(ui->btnBrowserFonts, SIGNAL(clicked()), this, SLOT(setWebFont()));

    // setup the form
    AppFactory::checkSettings();
    ui->checkMinimized->setChecked(AppFactory::settings->value("startMinimized", false).toBool());
    ui->checkInterval->setChecked(AppFactory::settings->value("updateAutomatically", true).toBool());
    ui->spinInterval->setValue(AppFactory::settings->value("updateInterval", 1800000).toInt() / 60000);
    ui->checkStartup->setVisible(false);
    ui->checkOpenBrowserRightClick->setChecked(AppFactory::settings->value("rightClickbrowser", false).toBool());

    AppFactory::settings->beginGroup("Proxy");
    ui->txtProxyHost->setText(AppFactory::settings->value("proxyHost").toString());
    ui->txtProxyName->setText(AppFactory::settings->value("proxyName").toString());
    ui->txtProxyPassword->setText(AppFactory::settings->value("proxyPass").toString());
    ui->spinPort->setValue(AppFactory::settings->value("proxyPort", 80).toInt());
    ui->cmbProxyType->setCurrentIndex(AppFactory::settings->value("proxyType", 0).toInt());
    AppFactory::settings->endGroup();

    ui->checkUpdateAfter->setChecked(AppFactory::settings->value("updateAfter", false).toBool());
    ui->txtBrowserArgs->setText(AppFactory::settings->value("browserArgs", DEFAULT_ARGS).toString());

    fontWeb.setFamily(AppFactory::webSettings->fontFamily(QWebSettings::StandardFont));
    fontWeb.setPointSize(AppFactory::webSettings->fontSize(QWebSettings::DefaultFontSize));

    ui->lblBrowserFonts->setText(tr("%1, size %2").arg(fontWeb.family(),
                                                       QString::number(fontWeb.pointSize())));

    QDir myDir(APP_LANG_PATH);
    ui->listLanguage->addItem("rssguard_en.qm");
    ui->listLanguage->addItems(myDir.entryList(QDir::Files | QDir::NoDotAndDotDot));

    QList<QListWidgetItem*> list = ui->listLanguage->findItems(AppFactory::settings->value("currentLanguage", "rssguard_en.qm").toString(), Qt::MatchExactly);
    if (list.size())
        ui->listLanguage->setCurrentItem(list.at(0));
    else
        ui->listLanguage->setCurrentItem(ui->listLanguage->item(0));

    ui->txtBrowser->setText(AppFactory::settings->value("browser", "").toString());
    ui->checkBrowser->setChecked(AppFactory::settings->value("useBrowser", ui->checkBrowser->isChecked()).toBool());

    ui->radioUseTab->setChecked(AppFactory::settings->value("useNewTab", true).toBool());
    ui->radioUseBrowser->setChecked(!AppFactory::settings->value("useNewTab", true).toBool());

    ui->radioOpenWebsite->setChecked(AppFactory::settings->value("openWebsite", true).toBool());
    ui->radioOpenSimple->setChecked(!AppFactory::settings->value("openWebsite", true).toBool());

    ui->spinTimeout->setValue(AppFactory::settings->value("updateTimeout", DEF_TIMEOUT).toInt());
	ui->checkUpdate->setChecked(AppFactory::settings->value("checkForUpdate", false).toBool());

    ui->checkUpdateOnStart->setChecked(AppFactory::settings->value("updateOnStart", true).toBool());
    ui->checkTabButton->setChecked(AppFactory::settings->value("tabsMidButton", true).toBool());

	ui->checkCenterSelection->setChecked(AppFactory::settings->value("centerSelection", true).toBool());

	ui->cmbUpdateInfo->setCurrentIndex(AppFactory::settings->value("displayUpdateInfo", 0).toInt());

    if (AppFactory::settings->value("feedFileNamePath", CONFIG_UNKNOWN).toString() != CONFIG_UNKNOWN) {
        ui->btnCustomPath->setEnabled(true);
        ui->txtCustomPath->setEnabled(true);
        ui->checkCustomPath->setChecked(true);
        ui->txtCustomPath->setText(AppFactory::settings->value("feedFileNamePath", CONFIG_UNKNOWN).toString());
    }

    if (!ui->radioUseTab->isChecked()) {
        ui->radioOpenSimple->setEnabled(false);
        ui->radioOpenWebsite->setEnabled(false);
    }

    ui->checkDeleteOnExit->setChecked(AppFactory::settings->value("deleteReadOnExit", false).toBool());

    // display checkbox for starting rssg automatically only on Windows
#if defined(Q_WS_WIN)
    ui->checkStartup->setVisible(true);
    QSettings sett("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    if (sett.value("RSSGuard", "").toString().replace('\\', '/') == QApplication::applicationFilePath())
        ui->checkStartup->setChecked(true);
#endif
}

FormSettings::~FormSettings() {
    delete ui;
}

void FormSettings::setEchoPassword() {
    if (ui->checkProxyPassword->isChecked())
        ui->txtProxyPassword->setEchoMode(QLineEdit::Normal);
    else
        ui->txtProxyPassword->setEchoMode(QLineEdit::Password);
}

void FormSettings::enableProxy(int type) {
    bool enable = type == 0 || type == 1;
    ui->txtProxyHost->setEnabled(!enable);
    ui->txtProxyName->setEnabled(!enable);
    ui->txtProxyPassword->setEnabled(!enable);
    ui->spinPort->setEnabled(!enable);
    ui->checkProxyPassword->setEnabled(!enable);
}

void FormSettings::enableBrowser() {
    if (ui->radioUseBrowser->isChecked()) {
        ui->checkBrowser->setEnabled(true);
    }
    else {
        ui->checkBrowser->setEnabled(false);
    }
}

void FormSettings::selectBrowser() {
    QString filterEnd;
#if defined(Q_WS_X11) || defined(Q_WS_MAC)
    filterEnd = " (*);;";
#endif
#if defined(Q_WS_WIN)
    filterEnd = " (*.exe);;";
#endif
    QString fileName = QFileDialog::getOpenFileName(this, tr("Select browser"), QDir::homePath(),
                                                    tr("Executable files") + filterEnd);
    if (fileName != NULL)
        ui->txtBrowser->setText(fileName);
}

void FormSettings::selectCustomFile() {
    QString fileName = QFileDialog::getSaveFileName(this, tr("Select custom feeds file"), QDir::homePath(),
                                                    tr("All files(*.*);;XML files(*.xml);;RSS Guard XML (*.rgx);;"));
    if (!fileName.size()) return;
    ui->txtCustomPath->setText(fileName);
}

void FormSettings::setWebFont() {
    bool ok;
    QFont font = QFontDialog::getFont(&ok, fontWeb, this,
                                      tr("Select font for internal web browser"));
    if (ok) {
        fontWeb = font;
        ui->lblBrowserFonts->setText(tr("%1, size %2").arg(fontWeb.family(),
                                                           QString::number(fontWeb.pointSize())));
    }
}

void FormSettings::informArgs() {
    if (ui->txtBrowserArgs->text().contains(DEFAULT_ARGS)) {
        ui->txtBrowserArgs->setToolTip(tr("It's okay, arguments contain \"%u\""));
        ui->txtBrowserArgs->setStyleSheet("QLineEdit { background-color: none; }");
    }
    else {
        ui->txtBrowserArgs->setToolTip(tr("Arguments should contain \"%u\". Its variable, which represents clicked message."));
        ui->txtBrowserArgs->setStyleSheet("QLineEdit { background-color: red; }");
    }
}

void FormSettings::checkBrowser() {
    if (QFile::exists(ui->txtBrowser->text())) {
        ui->lblBrowserExist->setStyleSheet("QLabel { margin-left: 30px;color: green; }");
        ui->lblBrowserExist->setText(tr("Selected file exists."));
    }
    else {
        ui->lblBrowserExist->setStyleSheet("QLabel { margin-left: 30px;color: red; }");
        ui->lblBrowserExist->setText(tr("Selected file doesn't exist."));
    }
}

void FormSettings::saveSettings() {
    AppFactory::settings->setValue("startMinimized", ui->checkMinimized->isChecked());
    AppFactory::settings->setValue("updateAutomatically", ui->checkInterval->isChecked());
    AppFactory::settings->setValue("updateInterval", ui->spinInterval->value() * 60000);
    if (ui->listLanguage->currentItem())
        AppFactory::settings->setValue("currentLanguage", ui->listLanguage->currentItem()->text());
    AppFactory::settings->setValue("browser", ui->txtBrowser->text());
    AppFactory::settings->setValue("useBrowser", ui->checkBrowser->isChecked());
    AppFactory::settings->setValue("rightClickbrowser", ui->checkOpenBrowserRightClick->isChecked());

    AppFactory::settings->setValue("useNewTab", ui->radioUseTab->isChecked());
    AppFactory::settings->setValue("openWebsite", ui->radioOpenWebsite->isChecked());

    AppFactory::settings->setValue("updateTimeout", ui->spinTimeout->value());

    AppFactory::settings->setValue("deleteReadOnExit", ui->checkDeleteOnExit->isChecked());
    AppFactory::settings->setValue("updateOnStart", ui->checkUpdateOnStart->isChecked());

	AppFactory::settings->setValue("checkForUpdate", ui->checkUpdate->isChecked());
    AppFactory::settings->setValue("updateAfter", ui->checkUpdateAfter->isChecked());
    AppFactory::settings->setValue("tabsMidButton", ui->checkTabButton->isChecked());

	AppFactory::settings->setValue("displayUpdateInfo", ui->cmbUpdateInfo->currentIndex());

    AppFactory::settings->beginGroup("Proxy");
    AppFactory::settings->setValue("proxyHost", ui->txtProxyHost->text());
    AppFactory::settings->setValue("proxyName", ui->txtProxyName->text());
    AppFactory::settings->setValue("proxyPass", ui->txtProxyPassword->text());
    AppFactory::settings->setValue("proxyPort", ui->spinPort->value());
    AppFactory::settings->setValue("proxyType", ui->cmbProxyType->currentIndex());
    AppFactory::settings->endGroup();

    AppFactory::settings->setValue("browserArgs", ui->txtBrowserArgs->text());

	AppFactory::settings->setValue("centerSelection", ui->checkCenterSelection->isChecked());

    AppFactory::webSettings->setFontFamily(QWebSettings::StandardFont, fontWeb.family());
    AppFactory::webSettings->setFontSize(QWebSettings::DefaultFontSize, fontWeb.pointSize());

    if (ui->checkCustomPath->isChecked())
        AppFactory::settings->setValue("feedFileNamePath", ui->txtCustomPath->text());
    else
        AppFactory::settings->setValue("feedFileNamePath", CONFIG_UNKNOWN);

#ifdef Q_WS_WIN
    QSettings sett("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
    if (ui->checkStartup->isChecked())
        sett.setValue("RSSGuard", QApplication::applicationFilePath().replace('/', '\\'));
    else
        sett.setValue("RSSGuard", "");
#endif

    AppFactory::checkSettings();
}
